package controllers

import (
	"MaternalBaby/api/models"
	"time"
)

type Person struct {
	BaseController
}

// @router /add [get]
func (c *Person) Add() {
	var m models.Person
	err := c.ParseForm(&m)
	if err != nil {
		c.Fail(1, err)
		return
	}

	if m.Id == 0 {
		m.CreatorId = c.u.Id
		_, err = o.Insert(&m)
		if err != nil {
			c.Fail(2, err)
			return
		}

		_, err = o.Insert(&models.Guardian{PId: m.Id, UId: c.u.Id})
		if err != nil {
			c.Fail(3, err)
			return
		}
	} else {
		_, err = o.Update(&m, "Name", "Avatar", "Birthday", "Sex")
		if err != nil {
			c.Fail(3, err)
			return
		}

	}
	c.Success("")
}

// @router /list [get]
func (c *Person) List() {
	var list []models.Person
	o.Raw("select * from person where id in(select p_id from guardian where u_id=?)", c.u.Id).QueryRows(&list)

	timeStart := time.Now().Add(-24 * time.Hour)
	for i, v := range list {
		o.QueryTable("Record").Filter("PId", v.Id).Filter("RecordTime__gte", timeStart).OrderBy("-RecordTime").All(&list[i].RecordList)
		list[i].G()
	}
	c.Success(list)
}

// @router /info [get]
func (c *Person) Info() {
	id, _ := c.GetInt("id")

	var m models.Person
	o.QueryTable(m).Filter("Id", id).One(&m)
	c.Success(m.G())
}

// @router /delete [get]
func (c *Person) Delete() {
	id, _ := c.GetInt("id")
	_, err := o.Delete(&models.Person{Id: id})
	if err != nil {
		c.Fail(1, err)
		return
	}
	c.Success("")
}

// @router /addGuardian [get]
func (c *Person) AddGuardian() {
	pId, _ := c.GetInt("pId")

	var m models.Guardian
	err := o.QueryTable(m).Filter("PId", pId).Filter("UId", c.u.Id).One(&m)
	if err == nil {
		c.Fail(1, "你已经是监护人了")
		return
	}

	m.UId = c.u.Id
	m.PId = pId

	o.Insert(&m)
	c.Success("成功")
}

// @router /guardianList [get]
func (c *Person) GuardianList() {
	pId, _ := c.GetInt("pId")

	var list []models.User
	o.Raw("select * from user where id in(select u_id from guardian where p_id=?)", pId).QueryRows(&list)
	for i, v := range list {
		list[i] = v.Summary()
	}
	c.Success(list)
}
